package com.dsteiner.xelavos.client.controller;

import java.util.Date;

import com.dsteiner.widgets.client.JsUtil;
import com.dsteiner.widgets.client.StringUtil;
import com.dsteiner.widgets.client.Widgets.IButton;
import com.dsteiner.widgets.client.Widgets.ILazyWidget;
import com.dsteiner.widgets.client.Widgets.IListBox;
import com.dsteiner.widgets.client.Widgets.IWidget;
import com.dsteiner.widgets.client.Widgets.TextInput;
import com.dsteiner.widgets.client.Widgets.WidgetListenerAdapter;
import com.dsteiner.widgets.client.event.EventManagerImpl;
import com.dsteiner.xelavos.client.SavedSearchWidget.SavedSearchModel;
import com.dsteiner.xelavos.client.domain.SavedSearch;
import com.dsteiner.xelavos.client.event.SavedSearchEvent;
import com.dsteiner.xelavos.client.model.AuthenticationModel;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;

public class SavedSearchController {

	private SavedSearchModel savedSearchModel;
	private IListBox frequencyListBox;
	private IListBox sendIfNoMatchesListBox;
	private TextInput nameTextBox;
	private AuthenticationModel authenticationModel;

	public void registerSavedSearchWidget(ILazyWidget savedSearchWidget) {
		savedSearchWidget.addWidgetListener(new WidgetListenerAdapter() {
			@Override
			public void onAttach(IWidget widget) {
			}
		});
	}

	public void registerSavedSearchModel(SavedSearchModel savedSearchModel) {
		this.savedSearchModel = savedSearchModel;
	}

	public void registerFrequencyListBox(IListBox frequencyListBox) {
		this.frequencyListBox = frequencyListBox;
	}

	public void registerSendIfNoMatchesListBox(IListBox sendIfNoMatchesListBox) {
		this.sendIfNoMatchesListBox = sendIfNoMatchesListBox;
	}

	public void registerNameTextBox(TextInput nameTextBox) {
		this.nameTextBox = nameTextBox;
	}

	public void registerSaveButton(IButton saveButton) {
		saveButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				String name = nameTextBox.getText();
				if(StringUtil.isEmpty(name)){
					JsUtil.getInstance().showAlert("Ingrese un nombre para guardar la busqueda");
					return;
				}
				
				boolean emailIfNoMatches = sendIfNoMatchesListBox.getSelectedItem().equals(SavedSearch.EMAIL_IF_NO_MATCHES_YES);
				String frequency = frequencyListBox.getSelectedItem();
				
				SavedSearch savedSearch = new SavedSearch();
				savedSearch.setRegisteredDate(new Date());
				savedSearch.setLastSentDate(new Date());
				savedSearch.setName(name);
				savedSearch.setEmailIfNoMatches(emailIfNoMatches);
				savedSearch.setFrequency(frequency);
				savedSearch.setUserId(authenticationModel.getUser().getId());
				
				EventManagerImpl.getInstance().fireEvent(new SavedSearchEvent(savedSearch));
			}
		});
	}

	public void registerAuthenticationModel(AuthenticationModel authenticationModel) {
		this.authenticationModel = authenticationModel;
	}
}